<?php

namespace app\home\controller;

use app\home\model\UserOrder;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Cache;
use think\Request;

class Pay800046 extends BasePay
{

    const CLIENT_ID = 111637981; //就是appid 和 appsecret
    const CLIENT_SECRET = 'aa9cacae9cef49c48caf78280447676e768720da9e902a6f922f9ee193b6eb04';
    

    public function test(){
        $Huawei = new \app\home\service\Huawei(self::CLIENT_ID,self::CLIENT_SECRET);
        $res = $Huawei->get_token();
        var_dump($res);die;
    }


    public function order()
    {
        parent::order();

        $data_Arr['code'] = 'success';

        $return['requestId'] = $this->order_array['id'];
        // 华为的配置为字母a+计费点 如a1000 a3000（看具体配置）
        $return['ProductId'] = $this->order_array['goods_id'];
        $return['amount'] = $this->order_array['amount']*100;

        $data_Arr['data'] = $return;

        putsuccess($data_Arr);

    }

    public function notify()
    {
        parent::notify();
        $params = Request::instance()->param();
        mylog($params);
        try{

            // 华为接口验证订单
            $res = $this->verify_order($params["token"],$params["productId"]);
            $data = json_decode($res,true);
            if(empty($res) || empty($data['purchaseTokenData'])){
                throw new \Exception('purchaseState empty');
            }
            $purchaseTokenData = json_decode($data['purchaseTokenData'],true);
            $order_amount = explode('=',$purchaseTokenData['developerPayload']);
            if($purchaseTokenData['purchaseState'] != 0){
                throw new \Exception('purchaseState false');
            }

            $notifyService = new NotifyService();
            $order_info = $notifyService->checkOrder($order_amount[0],$order_amount[1]/100);
            if($order_info == false){
                throw new \Exception('checkOrder false');
            }
            // 状态已经处理的订单直接返回成功
            if ($order_info["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("订单已经处理过了");
                return "success";
            }

            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id' =>$order_amount[0]])->find();
            if ($tradeLog) {
                $tradeLog->transactionID = $purchaseTokenData['orderId'];
                $tradeLog->save();
            }
            

            // 发货
            if($notifyService->notifyProcess($order_info) == false){
                throw new \Exception('notifyProcess false');
            }

            // 通知华为确认购买
            $this->confirm_order($params["token"],$params["productId"]);

            return "success";
        }catch(\Exception $exception){
            mylog('Pay800046-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return "error";
        }
    }


    public function get_token(){

        $huaweitoken = Cache::get('huaweitoken');
        if(!empty($huaweitoken)){
            return  $huaweitoken;
        }


        $url = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
        $data['grant_type'] = 'client_credentials';
        $data['client_id'] = self::CLIENT_ID;
        $data['client_secret'] = self::CLIENT_SECRET;

        $curlPost = http_build_query($data);
        $headers = array(
            "Content-Type: application/x-www-form-urlencoded",
        );

        $postUrl = $url;
        $curl = curl_init(); //初始化curl
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0); //设置header
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1); //post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); //提交的参数
        $json = curl_exec($curl); //运行curl
        curl_close($curl);
        mylog($json);
        if($json == false){
            mylog('token curl fail');
            return false;
        }

        $res = json_decode($json,true);
        if($res['responseCode'] != 0){
            mylog('token fail');
            return false;
        }

        $json = json_decode($json,true);

        Cache::set('huaweitoken',$json['access_token'],$json['expires_in']-60*10);

        return $json['access_token'];
    }

    /**
     * 通知华为确认购买
     *
     * @param [type] $purchaseToken
     * @param [type] $productId
     * @return boolean
     */
    public function confirm_order($purchaseToken,$productId){
        $url = "https://orders-drcn.iap.hicloud.com/applications/v2/purchases/confirm";
        $data = array('purchaseToken'=>$purchaseToken,'productId'=>$productId);
        $curlPost = json_encode($data);

        $headers = array(
            "Content-Type: application/json; charset=UTF-8",
            "Authorization: Basic " . base64_encode('APPAT:'.$this->get_token())
        );

        $postUrl = $url;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);//提交的参数
        $return = curl_exec($curl);//运行curl
        curl_close($curl);
        mylog("通知地址：{$url}");
        mylog("华为确认订单结果：");
        mylog($return);
        return true;
    }

    public function verify_order($purchaseToken,$productId){
        $url = "https://orders-drcn.iap.hicloud.com/applications/purchases/tokens/verify";
        $data = array('purchaseToken'=>$purchaseToken,'productId'=>$productId);
        $curlPost = json_encode($data);

        $headers = array(
            "Content-Type: application/json; charset=UTF-8",
            "Authorization: Basic " . base64_encode('APPAT:'.$this->get_token())
        );

        $postUrl = $url;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);//提交的参数
        $return = curl_exec($curl);//运行curl
        mylog("通知地址：{$url}");
        mylog("华为token结果：");
        mylog($return);
        curl_close($curl);

        return $return;


        if($return == false){
            mylog($return);
            return false;
        }

        $response_array = json_decode($return,true);
        if($response_array['responseCode'] != 0){
            return false;
        }

        return true;
    }
}
